package com.dominator.service.impl;

import com.dominator.service.CommonService;
import com.dominator.utils.exception.ApiException;
import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.typewrap.impl.HashDto;
import com.dominator.enums.ReqEnums;
import com.dominator.utils.api.ApiMessage;
import com.dominator.utils.api.ApiMessageUtil;
import com.dominator.utils.dao.RedisUtil;
import com.dominator.utils.system.PropertiesLoader;
import config.AppConfig;
import lib.MESSAGEXsend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import utils.ConfigLoader;

import java.util.Random;

@Service
public class CommonServiceImpl implements CommonService {

    private static final Logger log = LoggerFactory.getLogger(CommonServiceImpl.class);

    private static PropertiesLoader propertiesLoader = new PropertiesLoader("sysconfig.properties");

    private static RedisUtil ru = RedisUtil.getRu();

    /**
     * 发手机验证码
     *
     * @param dto phone String 必传 手机号
     * @return
     */
    @Override
    public ApiMessage sendMessage(Dto dto) throws ApiException {
        String phone = dto.getString("phone");
        //限制每个手机号24小时内的发送次数
        if (ru.exists(phone + "times") && Integer.valueOf(ru.get(phone + "times")) >= propertiesLoader.getInteger("message_times_in24hour")) {
            throw new ApiException(ReqEnums.REQ_PARAM_ERROR.getCode(),
                    ReqEnums.REQ_PARAM_ERROR.getMsg() + phone + "request more than 10 times in 24 hours");
        }
        AppConfig config = ConfigLoader.load(ConfigLoader.ConfigType.Message);
        MESSAGEXsend submail = new MESSAGEXsend(config);
        Random r = new Random();
        int[] n = {r.nextInt(10), r.nextInt(10), r.nextInt(10), r.nextInt(10)};
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n.length; i++) {
            sb.append(n[i]);
        }
        submail.addTo(phone);
        submail.setProject("sVm6R4");
        submail.addVar("code", sb.toString());
        submail.addVar("time", "5");
        submail.xsend();

        ru.setex(phone + "code", sb.toString(), propertiesLoader.getInteger("message_valid_time"));

        int times = 1;
        if (ru.exists(phone + "times")) {
            times = Integer.valueOf(ru.get(phone + "times")) + 1;
            ru.set(phone + "times", times + "");
        } else {
            ru.setex(phone + "times", times + "", 24 * 60 * 60);
        }
        log.info("code:{}", sb.toString());
        Dto resDto = new HashDto();
        resDto.put("phone", phone);
        resDto.put("code", sb.toString());
        return ApiMessageUtil.success(resDto);
    }

    /**
     * 校验手机验证码
     *
     * @param dto phone String 必传 手机号
     *            code String 必传 验证码
     * @return
     */
    @Override
    public ApiMessage checkMessage(Dto dto) throws ApiException {
        String phone = dto.getString("phone");
        String code = dto.getString("code");
        if (!ru.exists(phone + "code") || !code.equals(ru.get(phone + "code"))){
            throw new ApiException(ReqEnums.REQ_INCORRECT_CODE.getCode(), ReqEnums.REQ_INCORRECT_CODE.getMsg());
        }
        return ApiMessageUtil.success();
    }

    //	/**
//	 * ƥ�䴫���phone,code�Ƿ���session�е�phoneNo,codeNoһ��
//	 * @param userCode
//	 * @return
//	 */
//	@Override
//	@SuppressWarnings({ "rawtypes", "unchecked" })
//	public Boolean match(UserCode userCode, UserCode userCodeExists) {
//		if(userCode.equals(userCodeExists)){
//			return true;
//		}
//		return false;
//	}
//
//	/**
//	 * ����phone�ֻ��ţ���ȡcode��֤��
//	 * @param phone
//	 * @return
//	 */
//	@Override
//	public String sendMessage(String phone) throws Exception{
//		AppConfig config = ConfigLoader.load(ConfigLoader.ConfigType.Message);
//		MESSAGEXsend submail = new MESSAGEXsend(config);
//		Random r = new Random();
//		int[] n = {r.nextInt(10), r.nextInt(10), r.nextInt(10), r.nextInt(10)};
//		StringBuilder sb = new StringBuilder();
//		for(int i = 0; i < n.length; i++){
//			sb.append(n[i]);
//		}
//		System.out.println(sb.toString());
//		submail.addTo(phone);
//		submail.setProject("sVm6R4");
//		submail.addVar("code", sb.toString());
//		submail.addVar("time", "5");
//		submail.xsend();
//		return sb.toString();
//	}

}
